import { Injectable, NestInterceptor, ExecutionContext, CallHandler, BadGatewayException, HttpStatus } from '@nestjs/common';
import { Observable, throwError, of } from 'rxjs';
import { tap, map, catchError } from 'rxjs/operators';

import RSA from '../common/rsa'
import utils from 'src/common/utils';
import { login_code } from 'src/setting';
@Injectable()
export class ValidUniqueLoginInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.switchToHttp().getRequest();
    const res = context.switchToHttp().getResponse();

    const callError = (message) => {
      const status = HttpStatus.UNAUTHORIZED;
      const errorResponse = {
        message: message,
        status: status, // 自定义code
        url: req.originalUrl, // 错误的url地址
      };
      return errorResponse
    }
    let token = req.headers.wx_user_token
    if(!token) {
      let message = '非法操作'
      return of(callError(message));
    }else{
      if(req.method.toString().toLowerCase() === 'get'){
        return next.handle().pipe(
          map(data => {
            return data
          })
        );
      }
      //验证rsa
      try{
        let body = req.query
        if(req.method.toString().toLowerCase() === 'post'){
          body = JSON.parse(JSON.stringify(req.body))
        }
        let newBody = {}
        let loop = (data, key) => {
          if(data[key] === undefined || data[key] === null){
            delete data[key]
          }
          if(typeof(data[key]) === 'number'){
            data[key] = data[key].toString()
          }
          if(data[key]){
            if(typeof(data[key]) === 'string'){
              data[key] = utils.utf16toEntities(data[key])
            }else if(typeof(data[key]) === 'object'){
              for(let keyTwo in data[key]){
                loop(data[key], keyTwo)
              }
            }
          }
        }
        for(let key in body){
          newBody[key] = body[key]
          if(newBody[key] && typeof(newBody[key]) === 'string' && newBody[key].length > 200){
            newBody[key] = newBody[key].substring(0,200)
          }
          if(newBody[key] === undefined || newBody[key] === null){
            delete newBody[key]
          }
          if(typeof(newBody[key]) === 'number'){
            newBody[key] = newBody[key].toString()
          }
          if(newBody[key]){
            loop(newBody, key)
          }
        }
        let method = req.route.methods.get ? 'get' : req.route.methods.post ? 'post' : ''
        method = method.toLocaleUpperCase()
        let path = req.route.path
        let list = JSON.parse(login_code)
        let isValid = list.find(e => {
          let context = `${method}\n${path}\n${JSON.stringify(newBody)}\n${utils.user_token_key}\n${e}\n`
          console.log(context, 'context')
          return RSA.Decrypt(token, context)
        })
        if(!isValid){
          throw new Error('无权限。')
        }
        return next.handle().pipe(
          map(data => {
            return data
          })
        );
      }catch(err) {
        return of(callError(err.toString()));
      }

    }
  }
}
